package main

import (
	"context"
	service "grpc_study/hello_server/proto"

	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
)

// 实现PerRPCCredentials接口
type ClientTokenAuth struct{}

func (c ClientTokenAuth) GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error) {
	return map[string]string{
		"appId":  "alm.cn",
		"appKey": "abc123",
	}, nil
}

func (c ClientTokenAuth) RequireTransportSecurity() bool {
	// 暂不开启TLS验证
	return false
}

func main() {
	// 第一个参数传入证书，第二个参数传入域名（与openssl.cfg中配置的DNS.1 = *.alm.cn一致）
	// creds, _ := credentials.NewClientTLSFromFile("D:\\dev\\golang\\grpc\\kuangshen\\code\\01_grpc_study\\secure\\test.pem", "*.alm.cn")
	// 必须要指定一个加密方式（哪怕是不加密）
	// conn, err := grpc.Dial("127.0.0.1:9000", grpc.WithTransportCredentials(creds))
	// 不加密（RequireTransportSecurity返回为true）
	// Dial的第二个参数是grpc.DialOption的切片，可以这样写
	var opts []grpc.DialOption
	opts = append(opts, grpc.WithTransportCredentials(insecure.NewCredentials()))
	opts = append(opts, grpc.WithPerRPCCredentials(new(ClientTokenAuth)))
	conn, err := grpc.Dial("127.0.0.1:9000", opts...)
	if err != nil {
		panic(err)
	}
	defer conn.Close()

	// 建立连接
	client := service.NewSayHelloClient(conn)
	resp, err := client.SayHello(context.Background(), &service.HelloRequest{RequestName: "alm"})
	if err != nil {
		panic(err)
	}
	println(resp.ResponseMessage)
}
